package com.example.service;

import io.etcd.jetcd.watch.WatchEvent;
import io.etcd.jetcd.watch.WatchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class SysClusterServiceImpl implements SysClusterService, InitializingBean, KeyListener {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private EtcdService etcdService;

    @Resource
    private SysServerService sysServerService;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.etcdService.putAutoLease(ROOT_PATH + sysServerService.getServerKey(), sysServerService.getServerKey().getBytes(StandardCharsets.UTF_8), 4);
        this.etcdService.watchPrefKey(ROOT_PATH, this);
    }

    @Override
    public void onNext(WatchResponse watchResponse) {
        List<WatchEvent> events = watchResponse.getEvents();
        for (WatchEvent event : events) {
            //加入到了集群
            if (event.getEventType() == WatchEvent.EventType.PUT) {
                logger.warn("集群节点: " + event.getKeyValue().getKey().toString(StandardCharsets.UTF_8) + " 加入了集群");
            }
            //离开了集群
            if (event.getEventType() == WatchEvent.EventType.DELETE) {
                logger.warn("集群节点: " + event.getKeyValue().getKey().toString(StandardCharsets.UTF_8) + " 离开了集群");
            }
        }
    }
}
